import { defineStore } from 'pinia'
import { store } from '@/store'
import { getDetailDictApi } from '@/api/dict'

export interface DictItem {
  label: string
  value: string | number
}

export interface DictState {
  cachedDicts: Map<string, DictItem[]>
  cachedKeys: Set<string>
}

export const useDictStore = defineStore('dict', {
  state: (): DictState => ({
    cachedDicts: new Map(),
    cachedKeys: new Set()
  }),
  getters: {
    getCachedKeys(): string[] {
      return Array.from(this.cachedKeys)
    }
  },
  actions: {
    async getCachedDict(code: string): Promise<DictItem[]> {
      return new Promise((resolve) => {
        if (this.cachedKeys.has(code)) return resolve(this.cachedDicts.get(code) as DictItem[])
        getDetailDictApi(code).then((response) => {
          const data = response.data as DictItem[]
          this.cachedKeys.add(code)
          this.cachedDicts.set(code, data)
          resolve(data)
        })
      })
    }
  }
})

export const useDictStoreWithOut = () => {
  return useDictStore(store)
}
